from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
import redis
from django.contrib.auth.mixins import LoginRequiredMixin
from pure_pagination import Paginator, PageNotAnInteger
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from apps.users.forms import LoginForm
# from apps.users.forms import UserInfoForm, ChangePwdForm
from apps.users.forms import RegisterGetForm, UploadImageForm, UserInfoForm, ChangePwdForm, UpdateMobileForm
# from apps.utils.YunPian import send_single_sms
# from apps.utils.random_str import generate_random
from MxOnline.settings import yp_apikey, REDIS_HOST, REDIS_PORT
from apps.users.models import UserProfile
from apps.operations.models import UserFavorite, Banner, UserMessage, UserCourse
from apps.organizations.models import CourseRrg, Teacher
from apps.courses.models import Course

class CustomAuth(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

class LoginView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        banners = Banner.objects.all()[:3]
        next = request.GET.get("next", "")
        return render(request, "login.html",{
            "next":next,
            "banners":banners
            })
    def post(self, request, *args, **kwargs):
       #表单验证
       login_form = LoginForm(request.POST)
       banners = Banner.objects.all()[:3]
       if login_form.is_valid():
           # 用于通过用户名或密码查询用户是否存在
            user_name = login_form.cleaned_data["username"]
            password = login_form.cleaned_data["password"]
            user = authenticate(username=user_name, password=password)
            # from apps.users.models import UserProfile
            # #1.通过用户名查询到用户
            # #2.需要先加密在通过加密的密码进行查询
            # user  = UserProfile.objects.get(username=user_name, password=password)
            if user is not None:
                #查询到用户
                login(request,user)
                #登录成功之后应该怎么返回页面
                #跳转到课程开始学习页面
                next = request.GET.get("next", "")
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect(reverse("index"))
            else:
                #未查询到用户
                return render(request, "login.html", {"msg":"用户名或密码错误", "login_form": "用户名或密码错误", "banners":banners})
       else:
           return render(request, "login.html", {"login_form": "用户名或密码错误", "banners":banners})


class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(reverse("index"))


class RegisterView(View):
    def get(self, request, *args, **kwargs):
        register_get_form = RegisterGetForm()
        return render(request, "register.html", {
            "register_get_form":register_get_form
        })

    def post(self, request, *args, **kwargs):
        return render(request, "register.html")


class UploadImageView(LoginRequiredMixin, View):
    login_url = "/login/"

    # def save_file(self, file):
    #     with open(r"D:/python1/project/MxOnline/media/head_image/uploaded.jpg", "wb") as f:
    #         for chunk in file.chunks():
    #             f.write(chunk)
    def post(self, request, *args, **kwargs):
        #处理用户上传的头像
        image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()
            return JsonResponse({
                "status":"success",
            })
        else:
            return JsonResponse({
                "status": "fail"
            })

        # files = request.FILES["image"]
        # self.save_file(files)
        #如果同一个文件上传多次，相同名称的文件应该如何处理

class UpdateMobileView(LoginRequiredMixin, View):
    login_url = "/login/"
    def post(self, request, *args, **kwargs):
        mobile_form = UpdateMobileForm(request.POST)
        if mobile_form.is_valid():
            mobile = mobile_form.cleaned_data["mobile"]
            #已经存在的记录不能重新使用
            if UserProfile.objects.filter(mobile=mobile):
                return JsonResponse({
                    "mobile":"该手机已经被注册"
                })
            user = request.user
            user.mobile = mobile
            user.username = mobile
            user.save()
            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse(mobile_form.errors)
class UserInfoView(LoginRequiredMixin, View):
    login_url = "/login/"
    def get(self, request, *args, **kwargs):
        captcha_form = RegisterGetForm()
        current_page = "info"
        return render(request, 'usercenter-info.html',{
            "captcha_form":captcha_form,
            "current_page":current_page
        })

    def post(self, request, *args, **kwargs):
        user_info_form = UserInfoForm(request.POST, instance=request.user)
        if user_info_form.is_valid():
            user_info_form.save()
            return JsonResponse({
                "status":"success"
            })
        else:
            return JsonResponse(user_info_form.errors)

class ChangePwdView(View):
    def post(self, request, *args, **kwargs):
        pwd_form = ChangePwdForm(request.POST)
        if pwd_form.is_valid():
            pwd1 = request.POST.get("password1","")
            # pwd2 = request.POST.get("password2","")
            #
            # if pwd1 ==pwd2:
            #     user = request.user
            #     user.set_password(pwd1)
            #     user.save()
            #     login(request, user)
            #     return JsonResponse({
            #         "status": "success",
            #     })
            # else:
            #     return JsonResponse({
            #         "status":"fail",
            #         "msg":"密码不一致"
            #     })
            user = request.user
            user.set_password(pwd1)
            user.save()
            # login(request, user)
            return JsonResponse({
                "status": "success",
            })
        else:
            return JsonResponse(pwd_form.errors)
class MyCourseView(LoginRequiredMixin, View):
    login_url = "/login/"
    def get(self, request, *args, **kwargs):
        current_page = "mycourse"
        my_courses = UserCourse.objects.filter(user=request.user)
        return render(request, "usercenter-mycourse.html",{
            "my_courses":my_courses,
            "current_page":current_page
        })


class MyFavOrgView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfav"
        org_list = []
        fav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
        for fav_org in fav_orgs:
            org = CourseRrg.objects.get(id=fav_org.fav_id)
            org_list.append(org)
        return render(request, "usercenter-fav-org.html", {
            "org_list":org_list,
            "current_page": current_page
        })



class MyFavTeacherView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfav_teacher"
        teacher_list = []
        fav_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
        for fav_teacher in fav_teachers:
            org = Teacher.objects.get(id=fav_teacher.fav_id)
            teacher_list.append(org)
        return render(request, "usercenter-fav-teacher.html", {
            "teacher_list":teacher_list,
            "current_page": current_page
        })



class MyFavCourseView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfav_teacher"
        course_list = []
        fav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
        for fav_course in fav_courses:
            course = Course.objects.get(id=fav_course.fav_id)
            course_list.append(course)
        return render(request, "usercenter-fav-course.html", {
            "course_list":course_list,
            "current_page": current_page
        })



class MyMessageView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "mymessage"
        messages_all = UserMessage.objects.filter(user=request.user)
        for message in messages_all:
            message.has_read = True
            message.save()
        # 对信息数据进行分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(messages_all, 5, request=request)

        messages = p.page(page)

        return render(request, "usercenter-message.html", {
            "messages":messages,
            "current_page":current_page
        })